package main

import (
	"sync"
	"time"
	"github.com/kataras/iris"
)

type Manager struct {
	sync.Mutex
	ctx 			*Context

	orderTicker 	*time.Ticker
	marketTicker 	*time.Ticker
	priceTicker 	*time.Ticker
}

func NewManager(ctx *Context) *Manager {
	manager := &Manager{
		ctx: 			ctx,
		orderTicker: 	time.NewTicker(3 * time.Second),
		marketTicker: 	time.NewTicker(5 * time.Second),
		priceTicker: 	time.NewTicker(3 * time.Second),
	}

	iris.RegisterOnInterrupt(func() {
		manager.orderTicker.Stop()
		manager.marketTicker.Stop()
		manager.priceTicker.Stop()
	})

	return manager
}

func (m *Manager) Run()  {
	go func() {
		for {
			select {
			case <-m.orderTicker.C:
				go m.handler(NewOrder(m.ctx))
			case <-m.marketTicker.C:
				go m.handler(NewMarket(m.ctx))
			case <-m.priceTicker.C:
				go refreshPrice(m.ctx)
			}
		}
	}()
}

func (m *Manager) handler(handler Handler)  {
	handler.run()
}